package com.funcourse.demo.wechat.client.welet;


import com.funcourse.demo.api.ApiSystemConstants;
import com.funcourse.demo.wechat.conf.WeletConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Component
public class CodeToSessionCaller {

  private static final String ADDRESS = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={jsCode}&grant_type=authorization_code";
  @Autowired
  RestTemplate restTemplate;

  @Autowired
  HttpServletRequest httpServletRequest;

  public Js2SessionResponse code2Session(String jsCode) {
    WeletConfiguration weletConfiguration = (WeletConfiguration)httpServletRequest.getAttribute(ApiSystemConstants.SERVLET_ATTR_WELET_CONFIG);
    return restTemplate.getForObject(ADDRESS, Js2SessionResponse.class,
        weletConfiguration.getAppId(), weletConfiguration.getAppSecret(), jsCode);
  }
}
